from simu_common import Cbid, getStepOptRevenue, bids_key, getOptRevenue
from simu_rng2 import get_uniform, get_poisson
from pylab import grid, show, plot, legend

#
#   Sensitive analysis of C
#

g_arr_rate = 5
g_periods = 50

def get_arrivals(rate, periods):
    '''
        Output: a serial of arrival bids numbers
    '''
    return get_poisson(rate, periods)
    
def get_bids(num):
    '''
        Output: a serial of arrival bids with given number
    '''
    bids = []
    vp = get_uniform(num)
    vs = get_uniform(num)
    for i in xrange(0, num):
        bids.append(Cbid(vp[i], vs[i]))
        
    return bids

def get_bids_flow(rate, T):
    arrs = get_arrivals(rate, T)
    num = sum(arrs)
    bids = get_bids(num)
    return arrs, bids
    
def exp_opt_revenue(v_arr, v_bids, k, tao, r0, y0, C):
    '''
    '''
    revenue = 0.0
    T = len(v_arr)
    bids = []
    cur_bid = 0
    for a in v_arr:
        for i in xrange(0, a):
            bids.append(v_bids[cur_bid])
            cur_bid = cur_bid + 1
        
        bids.sort(key=bids_key, reverse=True)
        revenue = revenue + getStepOptRevenue(bids, k, tao, r0, y0, C)
  
    return revenue/T
    
def exp_opt_revenue_l(v_arr, v_bids, k, tao, l, y0, C):
    '''
    '''
    revenue = 0.0
    T = len(v_arr)
    bids = []
    cur_bid = 0
    r0 = 0.0
 
    for a in v_arr:
    
        if l >= cur_bid:
            if cur_bid > 0:
                r0 = bids[cur_bid-1].r
            else:
                r0 = 0.05
        else:
            r0 = bids[l].r
            
        for i in xrange(0, a):
            bids.append(v_bids[cur_bid])
            cur_bid = cur_bid + 1
        
        bids.sort(key=bids_key, reverse=True)
        revenue = revenue + getStepOptRevenue(bids, k, tao, r0, y0, C)
        #print C, getOptRevenue(k-1, k, bids, tao, r0, y0)
  
    #debug=[]
    #for d in xrange(0, k):
    #    debug.append(getOptRevenue(d, k, bids, tao, r0, y0))
    #print C, debug
    return revenue/T  
    
def sensitive_c(rate, periods, step, k, r0, tao, y0, C0, Cn):
    '''
    '''
    v_arrs, v_bids = get_bids_flow(rate, periods)
    cs = []
    c = C0
    while c < Cn:
        cs.append(c)
        c = c + step
    
    rv0=[]
    rv1=[]
    rvk=[]
    
    for c in cs:
        rv0.append(exp_opt_revenue(v_arrs, v_bids, k, tao, r0, y0, c))
        rv1.append(exp_opt_revenue_l(v_arrs, v_bids, k, tao, 0, y0, c))
        rvk.append(exp_opt_revenue_l(v_arrs, v_bids, k, tao, k-1, y0, c))
    
    return cs, rv0, rv1, rvk
    
if __name__ == "__main__":
    
    cs, rv0, rv1, rvk = sensitive_c(g_arr_rate, g_periods, step=0.01, k=8, r0=0.01, tao=1.4, y0=1, C0=0.01, Cn=1)
    grid(True)
    plot(cs, rv0, 'b', cs, rv1, 'g', cs, rvk, 'r')
    show()
    